package org.siqisource.webstart.core.widgets.tree.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.siqisource.webstart.core.utils.condition.Condition;
import org.siqisource.webstart.core.widgets.tree.config.TreeConfig;
import org.siqisource.webstart.core.widgets.tree.constants.TreeConstants;
import org.siqisource.webstart.core.widgets.tree.constants.TreeNodeConstants;
import org.siqisource.webstart.core.widgets.tree.helper.TreeHelper;
import org.siqisource.webstart.core.widgets.tree.mapper.TreeMapper;
import org.siqisource.webstart.core.widgets.tree.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TreeService {

	/** 树操作类 */
	@Autowired
	private TreeMapper treeMapper = null;

	public Integer insertNode(TreeConfig treeConfig, Object node) {
		// 获得节点
		TreeNode treeNode = TreeHelper.getTreeNode(treeConfig, node);

		Integer parentNodeId = treeNode.getParentId();

		Integer sortNo = treeNode.getSortNo();
		boolean isNeedUpdateBrotherSortNo = true;

		if (sortNo == null) {
			isNeedUpdateBrotherSortNo = false;
			sortNo = treeMapper.getNextSortNo(treeConfig, parentNodeId);
			treeNode.setSortNo(sortNo);
		}

		TreeNode parentNode = treeMapper.readNode(treeConfig, parentNodeId);

		String fullPath = TreeConstants.PATH_SEPARATOR;

		if (parentNode != null) {

			// 更新父节点是否叶子节点的状态
			if (parentNode.getIsLeaf()) {
				isNeedUpdateBrotherSortNo = false;
				treeMapper.updateIsLeaf(treeConfig, parentNodeId, false);
			}

			// 更新兄弟节点的sortNo
			if (isNeedUpdateBrotherSortNo) {
				treeMapper.updateSortNoBatch(treeConfig, parentNodeId, sortNo, 1);
			}

			// 记录父节点的全路径
			fullPath = parentNode.getFullPath();
		}

		// 插入节点
		Integer nodeId = treeNode.getId();
		if (nodeId != null) {
			fullPath += treeNode.getId() + TreeConstants.PATH_SEPARATOR;
			treeNode.setFullPath(fullPath);
			treeMapper.insertNodeWithNodeId(treeConfig, treeNode);
		} else {
			treeMapper.insertNode(treeConfig, treeNode);
			//更新全路径
			fullPath += treeNode.getId() + TreeConstants.PATH_SEPARATOR;
			treeMapper.updateFullPath(treeConfig, treeNode.getId(), fullPath);
		}
		
		return treeNode.getId();
	}

	public void deleteTreeNode(TreeConfig treeConfig, Integer nodeId) {

		TreeNode treeNode = treeMapper.readNode(treeConfig, nodeId);
		// 删除
		treeMapper.deleteNode(treeConfig, nodeId);
		// 更新旧父节点是否叶子节点状态
		Integer parentNodeId = treeNode.getParentId();
		if (treeMapper.readFirstChild(treeConfig, parentNodeId) == null) {
			treeMapper.updateIsLeaf(treeConfig, treeNode.getParentId(), true);
		}
		// 无主数据（将parentNodeId标记为负数）
		List<TreeNode> treeNodes = this.readChildren(treeConfig, nodeId, new Condition());
		for (TreeNode childTreeNode : treeNodes) {
			treeMapper.updateParentNodeId(treeConfig, childTreeNode.getId(), -nodeId);
		}
		// 批量更新无主数据的全路径
		treeMapper.updateOffspringFullPath(treeConfig, treeNode.getFullPath(), TreeConstants.PATH_SEPARATOR);

	}

	public void deleteTreeNodeCascade(TreeConfig treeConfig, Integer nodeId) {

		TreeNode treeNode = treeMapper.readNode(treeConfig, nodeId);
		// 删除
		treeMapper.deleteNodeCascade(treeConfig, nodeId);
		// 更新旧父节点是否叶子节点状态
		Integer parentNodeId = treeNode.getParentId();
		if (treeMapper.readFirstChild(treeConfig, parentNodeId) == null) {
			treeMapper.updateIsLeaf(treeConfig, treeNode.getParentId(), true);
		}
	}

	public void updateNodeLabel(TreeConfig treeConfig, Integer nodeId, String nodeLabel) {
		TreeNode oldTreeNode = treeMapper.readNode(treeConfig, nodeId);
		String oldNodeLabel = oldTreeNode.getName();

		if (!oldNodeLabel.equals(nodeLabel)) {
			treeMapper.updateNodeLabel(treeConfig, nodeId, nodeLabel);
			//Todo fireEvent
		}
	}

	public List<TreeNode> readChildren(TreeConfig treeConfig, Integer parentNodeId, Condition condition) {
		String parentNodeIdField = treeConfig.getFieldParentId();
		if(condition == null){
			condition = new Condition();
		}
		condition.singleValue("and", "", parentNodeIdField, "=", parentNodeId, "");
		List<TreeNode> nodeList = treeMapper.readNodes(treeConfig, condition);
		return nodeList;
	}

	public List<Map<String, Object>> readChildrenWithContent(TreeConfig treeConfig, String parentNodeId,
			Condition condition) {
		condition.singleValue("and", "", treeConfig.getFieldParentId(), "=", parentNodeId, "");
		return treeMapper.readNodesWithContent(treeConfig, condition);

	}

	public List<TreeNode> queryByKeyWord(TreeConfig treeConfig, String keyWord, Condition condition) {

		Condition parentCondition = condition.copy();
		condition.singleValue("AND", "", treeConfig.getFieldName(), "LIKE", "%" + keyWord + "%", "");
		List<TreeNode> result = treeMapper.readNodes(treeConfig, condition);
		if (result.size() == 0) {
			return result;
		}
		String replaceDestString = TreeNodeConstants.MATCH_WORD_BEGIN + keyWord + TreeNodeConstants.MATCH_WORD_END;

		List<Integer> matchedNodeIds = new ArrayList<Integer>();
		for (TreeNode node : result) {
			// 修饰匹配的字符串
			String nodeName = node.getName();
			node.setName(nodeName.replace(keyWord, replaceDestString));
			// 收集已匹配的节点Id
			Integer nodeId = node.getId();
			matchedNodeIds.add(nodeId);
		}

		parentCondition.singleValue("AND", "", treeConfig.getFieldId(), "not in", matchedNodeIds, "");

		List<String> fullPathNodeIds = new ArrayList<String>();
		// 找到这些匹配的节点的父节点
		for (TreeNode node : result) {
			String fullPath = node.getFullPath();
			String[] parentIds = fullPath.split("/");
			for (int i = 0; i < parentIds.length - 1; i++) { // length-1表示不需要节点本身
				fullPathNodeIds.add(parentIds[i]);
			}
		}

		parentCondition.singleValue("AND", "", treeConfig.getFieldId(), "in", fullPathNodeIds, "");

		List<TreeNode> parentNodes = treeMapper.readNodes(treeConfig, parentCondition);
		if (parentNodes != null && parentNodes.size() > 0) {
			result.addAll(parentNodes);
		}
		return result;
	}

}
